#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "getputch.h"

#define MAX_STAGE 10

#define swap(type, x, y)   do { type z = x; x=y; y=z; } while (0)

int main(void)
{

    init_getputch();
    srand(time(NULL));

    int stage =0;

    int digits[9] = {1,2,3,4,5,6,7,8,9};

    time_t s,e;

    time(&s);

    puts("请填入缺少的数字(1~9).\n");
    fflush(stdout);

    for (;stage < MAX_STAGE; ++stage) {
        int goal = rand() % 9;

        int que[8];

        int i,j;
        for (i=j=0; i<9; ++i) {
            if (i != goal) {
                que[j++] = digits[i];
            }
        }

        for (i=7; i>0; --i) {
            int j = rand() % (i+1);
            if (i != j) swap(int, que[i], que[j]);
        }

        for (i=0; i<8; ++i) {
            printf("%d ", que[i]);
        }
        putchar(':');
        fflush(stdout);

        char goalc = digits[goal] + '0';

        int input;

        do {
            //scanf("%d", &input);
            input = getch();
            putch(input);

            printf(input != goalc ? "\a\b" : "\n");
            fflush(stdout);

        } while (input != goalc);

        puts("");
        fflush(stdout);
    }

    time(&e);

    int dur = (int)(e - s);

    printf("用时%d.\n", dur);

    if (dur > 25) {
        printf("反应太慢了.");

    } else if (dur > 20) {
        printf("反应有点慢.");

    } else if (dur > 17) {
        printf("反应不行吧");

    } else {
        printf("反应真快啊.");
    }

    puts("");

    getch();

    term_getputch();

    return 0;
}
